console.log("content script begin...");

var CssClassName = "";
var url = location.toString();
if(url == "https://plus.google.com"){
	CssClassName = "Wbhcze Te ch";
}else{
	CssClassName = "Wbhcze Te";
}
console.log("CssClassName: "+ CssClassName);

chrome.extension.sendRequest({}, function(response) {});


function addDownloadLink(node){
	
	var imgNodes = node.getElementsByClassName('Zbbru');
	var textNodes = node.getElementsByClassName('Sr');

	if(imgNodes && imgNodes.length == 1 && textNodes && textNodes.length == 1){
		var spareNode = document.createTextNode("   -   ");
		
		var child = document.createElement('a');
		child.innerText = 'download';
		
		var atrTag = document.createAttribute("target");
		atrTag.nodeValue = "_blank";
		child.setAttributeNode(atrTag);
	
		var atrHref = document.createAttribute("href");
		console.log(imgNodes[0]);
		var imgSrc = imgNodes[0].getElementsByTagName("img")[0].getAttributeNode("src").value;
		//imgSrc = imgSrc.replace("lh3", "lh5");
		
		var strList = imgSrc.split('/');
		console.log("before convert url to full size image"+strList);
		strList[strList.length-2]="s0-d";
		imgSrc = strList[0];
		for (var i=1; i<strList.length; i++){
			imgSrc += '/' + strList[i];
		}
		console.log("after convert url to full size image"+imgSrc);
		
		atrHref.nodeValue = "https:"+imgSrc;
		child.setAttributeNode(atrHref);
		/*
		var atrClass = document.createAttribute("class");
		atrClass.nodeValue = "c-C UuCFYe";
		child.setAttributeNode(atrClass);
		*/
	
		textNodes[0].appendChild(spareNode);
		textNodes[0].appendChild(child);
	
		console.log(textNodes[0]);
	}else{
		console.log("no append");
	}
}

var nodeList = document.getElementsByClassName(CssClassName);
console.log("selected node count: "+nodeList.length);
for(var i=0; i<nodeList.length; i++){
	addDownloadLink(nodeList[i]);
}

document.body.addEventListener('DOMNodeInserted', function (e) {
    console.log(e.target);
    if (e.target.nodeType != 3 && e.target.tagName == 'DIV' && e.target.className == CssClassName) {
		//console.log(e.target);
		addDownloadLink(e.target);
		
	}
}, false);

console.log("content script end...");